﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Mrc.Entity;
using Microsoft.AspNetCore.Http;
using DotNetEx;
using Microsoft.AspNetCore.Mvc.Filters;
using Mrc.Data;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Security.Claims;
namespace MrcWeb.Controllers
{
    public abstract class BaseController : Controller
    {
        AdminSession _session;

        [NonAction]
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
        }
        public AdminSession CurrentSession
        {
            get
            {
                if (this._session != null)
                    return this._session;
                AdminSession userSession = null;
                userSession = this.HttpContext.Items["user"] as AdminSession;
                this._session = userSession;
                return userSession;
            }
            set
            {
                AdminSession session = value;
                if (GlobalsConfig.cacheType == "redis")
                {
                    if (session == null)
                    {
                        return;
                    }
                    var key = (session.AccountName + ":" + GlobalsConfig.Configuration["Key:LoginInfoKey"]);
                    var token = EncryptHelper.AESEncrypt(key, GlobalsConfig.EncryptKey);
                    RedisHelper.Set(key, session.Serialize());
                    this.HttpContext.Response.Cookies.Append("MRCTOKEN", token, new CookieOptions
                    {
                        Expires = DateTime.Now.AddMinutes(30)
                    });
                }
                else
                {
                    if (session == null)
                    {
                        //注销登录
                        this.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                        return;
                    }
                    List<Claim> claims = session.ToClaims();
                    var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme));
                    this.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties
                    {
                        ExpiresUtc = DateTime.UtcNow.AddMinutes(60),
                        IsPersistent = false,
                        AllowRefresh = false
                    });
                }
                this.HttpContext.Items["islogin"] = true;
                this.HttpContext.Items["user"] = session;
                this._session = session;
            }
        }
    }
}
